import { reqCartList ,reqDeleteCartById,reqUpdateCheckedById} from "@/api";

const state ={
    cartList:[]
};
const mutations={
    GETCARTLIST(state,value){
        state.cartList=value
    }
};
const actions = {
    async getCartList(context){
        let result=await reqCartList();
        // console.log(result);
        if(result.code===200){
            context.commit('GETCARTLIST',result.data)
        }
    },
    async deleteCartListById(context,skuId){
        let result=await reqDeleteCartById(skuId);
        if(result.code===200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    async updateCheckedById(context,{skuId,isChecked}){
        let result=await reqUpdateCheckedById(skuId,isChecked);
        if(result.code===200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    async deleteAllCheckedCart(context){
        let promiseAll=[];
        let cartInfoList=context.getters.cartList.cartInfoList;
        if(!cartInfoList){
            cartInfoList=[]
        }
        cartInfoList.forEach(item => {
            if(item.isChecked===1){
              promiseAll.push(context.dispatch('deleteCartListById',item.skuId));
            }
        });
        return Promise.all(promiseAll);
    },
    //全选
    async updateCartAllChecked(context,isChecked){
        let promiseAll=[];
        let cartInfoList=context.getters.cartList.cartInfoList;
        if(!cartInfoList){
            cartInfoList=[]
        }
        cartInfoList.forEach(item => {
            if(item.isChecked!=isChecked){
            //   console.log(1);
              promiseAll.push(context.dispatch('updateCheckedById',{skuId:item.skuId,isChecked}));
            }
        });
        return Promise.all(promiseAll);
    }
};
const getters={
    cartList(state){
        return state.cartList[0]||{}
    },
};

export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}